/*
* 将jmx进行解析
* */


export default {


  // 根据根节点遍历寻找指定name的文本值（递归思想寻找）
  getValue(xmlDoc, rootNodeTag, findNodeName) {
    let result = {
      success: false,
      value: null
    };

    if (xmlDoc && rootNodeTag && findNodeName) {
      let rootNode = xmlDoc.getElementsByTagName(rootNodeTag)[0];
      result = this.getChildValue(rootNode, findNodeName);
    }

    return result;
  },
  // 从某节点的孩子节点下遍历寻找指定name的文本值
  getChildValue(parentNode, findNodeName) {
    let result = {
      success: false,
      value: null
    };

    if (parentNode && findNodeName) {
      console.log(28)
      console.log(parentNode)
      console.log(parentNode.childNodes)
      for (let i = 0; i < parentNode.childNodes.length; i++) {
        let child = parentNode.childNodes[i];
        console.log('35', child)
        debugger
        console.log(findNodeName)
        // console.log(child.getAttribute('name'))

        if (child.getAttribute('name') === findNodeName) {
          if (child.childNodes.length > 0) {
            result.success = true;
            result.value = child.childNodes[0].nodeValue;
          }
          break;
        } else if (this.hasChildNodes(child)) {
          let res = this.getChildValue(child, findNodeName);
          if (res.success) {
            result = res;
            break;
          }
        }
      }
    }

    return result;
  },
  // 判断节点是否有孩子节点（如果一个节点孩子节点为0或者孩子节点为1但该孩子节点类型为文本，认为没有孩子节点）
  hasChildNodes(node) {
    if (node) {
      return !(node.childNodes.length == 0 || (node.childNodes.length == 1 && node.childNodes[0].nodeType == 3))
    }
    return false;
  },
  // 获取各个节点
  print(xmlDoc, nodeName) {
    let result = this.getValue(xmlDoc, 'jmeterTestPlan', nodeName);
    // document.write('success: ' + result.success + ' ' + nodeName + ' = ' + result.value);
    // document.write("<br />");
    return result.value;

  },
  // 主逻辑开始
  getChidrenXML(text) {

    let parser = new DOMParser();
 
    let xmlDoc = parser.parseFromString(text, "text/xml");
  
 



    // 核心逻辑开始
    // this.print('TestPlan.tearDown_on_shutdown');
    // this.print('TestPlan.functional_mode');
    // this.print('HTTPSampler.domain');
    // this.print('ThreadGroup.num_threads');
    // this.print('HTTPSampler.protocol');
    // this.print('ThreadGroup.duration');

    let aList = ['TestPlan.tearDown_on_shutdown','TestPlan.functional_mode', 'HTTPSampler.domain', 'ThreadGroup.num_threads', 'HTTPSampler.protocol', 'ThreadGroup.duration']
    let resultObject = {}
    for (let a of aList) {
      resultObject[a] = this.print(xmlDoc, a)
      console.log(89)
      alert(89)

    }

    return resultObject
  }



}







